class Api::V1::CompaniesController < Api::V1::BaseController
  before_action :authenticate_request!

  def index
    render json: Company.all
  end

  def create
    begin
      @company = Company.new(create_params)
      authorize @company
      @company.save!
      render json: @company, status: 201
    rescue ActiveRecord::StatementInvalid
      @company.errors.add(:exec_error, '数据库错误，请联系管理员')
      error_render(@company, 403)
    rescue Pundit::NotAuthorizedError => err
      #error_render(err.record, 403)
      render status: 404
    rescue => err
      #error_render(err.record, 403)
      puts err
    end
  end

  def update
    begin
      @company = Company.find(params[:id])
      @company.update_attributes!(create_params)
      render json: @company, status: 200
    rescue => err
      error_render(err.record, 403)
    end
  end

  def destroy
    begin
      @company = Company.find(params[:id])
      @company.destroy!
      render status: 204
    rescue ActiveRecord::RecordNotFound
      render status: 404
    rescue => err
      error_render(err.record, 403)
    end
  end

  def show
    @company = Company.find(params[:id])
    render json: @company, status: 200
  end

  private

  def create_params
    params_parse(params)
  end

end
